from django_redis import get_redis_connection
from rest_framework.decorators import action
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

# Create your views here.
from apps.question.models import Label, Question, Reply
from apps.question.serializers import GetAllLableSerializer, QuestionSerializer, QuestionSerializerForCreate, \
    QuestionSerializerForDetail, ReplySerializerForCreate, LabelSerializerWithQuestionAndArticle, LabelSerializer


class GetAllLablesView(ModelViewSet):
    # 获取所有标签列表
    queryset = Label.objects.all()

    def retrieve(self, request, pk):

        label = self.get_object()
        s = LabelSerializerWithQuestionAndArticle(instance=label)
        return Response(s.data)

    # labels/  获取标签基本信息列表
    def list(self, request):
        labels = self.get_queryset()
        s = GetAllLableSerializer(instance=labels, many=True)
        return Response(s.data)

    @action(methods=['get'], detail=False)
    def full(self, request):
        labels = self.get_queryset()
        s = LabelSerializer(instance=labels, many=True)
        return Response(s.data)
    # 获取用户关注标签
    @action(methods=['GET'], detail=False)
    def users(self, request):
        try:
            user = request.user
        except:
            user = None
        if user.is_authenticated and user is not None:
            labels = user.labels.all()
            ser = GetAllLableSerializer(instance=labels, many=True)
            return Response(ser.data)
        else:
            return Response([])

    # 关注标签
    @action(methods=['PUT'], detail=True)
    def focusin(self, request,pk):
        try:
            user = request.user
        except Exception as e:
            return Response({"message": "收藏失败", "success": False})
        # 2. 判断用户是否登录
        if user.is_authenticated:
            # 用户登录成功  收藏信息保存
            label = Label.objects.get(id=pk)
            label.users.add(user)
            label.save()
            return Response({'success': True, 'message': '收藏成功'})
        else:
            return Response({'success': False, 'message': '未登录'})    \

    @action(methods=['PUT'], detail=True)
    def focusout(self, request,pk):
        try:
            user = request.user
        except Exception as e:
            return Response({"message": "收藏失败", "success": False})
        # 2. 判断用户是否登录
        if user.is_authenticated:
            # 用户登录成功  收藏信息保存
            label = Label.objects.get(id=pk)
            label.users.remove(user)
            label.save()
            return Response({'success': True, 'message': '收藏成功'})
        else:
            return Response({'success': False, 'message': '未登录'})

class QuestionView(ModelViewSet):
    # 指定查询集
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

    # 获取最新回答的问题
    @action(methods=["GET"], detail=True, url_path='label/new')
    def get_question_list(self, request, pk):
        if pk == '-1':
            questions = self.get_queryset().order_by("-replytime")
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all().order_by("-replytime")
        ser = QuestionSerializer(instance=questions, many=True)
        return Response(ser.data)

    # 获取最热回答的问题
    @action(methods=["GET"], detail=True, url_path="label/hot")
    def get_hot_question(self, request, pk):
        if pk == "-1":
            questions = Question.objects.all().order_by("-reply")
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all().order_by("-reply")
        ser = QuestionSerializer(instance=questions, many=True)
        return Response(ser.data)

    # 获取等待回答的问题
    @action(methods=["GET"], detail=True, url_path="label/wait")
    def get_wait_question(self, request, pk):
        if pk == "-1":
            questions = self.get_queryset()
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all()
        questions = questions.filter(reply=0).order_by("-createtime")
        ser = QuestionSerializer(instance=questions, many=True)
        return Response(ser.data)

    # 发布一个问题
    def create(self, request, *args, **kwargs):
        try:
            user = request.user
        except:
            user = None
        if user.is_authenticated and user is not None:
            data = request.data
            data['user'] = user.id
            ser = QuestionSerializerForCreate(data=data)
            ser.is_valid(raise_exception=True)
            ser.save()
            return Response({'success': True, 'message': '发表成功'})
        else:
            return Response({'success': False, 'message': '请先登录'}, status=400)

    # 问题详情获取
    def retrieve(self, request, *args, **kwargs):
        question = self.get_object()
        question.visits += 1
        question.comment_question = []
        question.answer_question = []
        replies = question.replies.all()
        for i in replies:
            if i.type == 0:  # 问题的评论
                question.comment_question.append(i)
            elif i.type == 2:  # 回答的评论
                question.answer_question.append(i)
        question.save()
        ser = QuestionSerializerForDetail(instance=question)
        return Response(ser.data)

    # 更新没用的回答
    @action(methods=['put'], detail=True)
    def useful(self, request, pk):
        try:
            user = request.user
        except:
            user = None
        # 判断登录
        if user.is_authenticated and user is not None:
            # 创建redis连接对象
            conn = get_redis_connection('question')
            # 查询标识数据,如果有,代表点击过
            flag = conn.hget('question_useful_%s' % user.id, pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            # 进行保存操作
            question = self.get_object()
            question.useful_count += 1
            question.save()
            # 设置一个是否点击过的标识
            conn.hset('question_useful_%s' % user.id, pk, '你的温柔无人能及')
            return Response({'success': True, 'message': '操作成功'})
        else:
            return Response({'success': False, 'message': '请先登录'})

    # 更新没用的回答
    @action(methods=['put'], detail=True)
    def unuseful(self, request, pk):
        try:
            user = request.user
        except:
            user = None
        # 判断登录
        if user.is_authenticated and user is not None:
            # 创建redis连接对象
            conn = get_redis_connection('question')
            # 查询标识数据,如果有,代表点击过
            flag = conn.hget('question_useful_%s' % user.id, pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            # 进行保存操作
            question = self.get_object()
            question.unuseful_count += 1
            question.save()
            # 设置一个是否点击过的标识
            conn.hset('question_useful_%s' % user.id, pk, '你的温柔无人能及')
            return Response({'success': True, 'message': '操作成功'})
        else:
            return Response({'success': False, 'message': '请先登录'})


class ReplyView(ModelViewSet):
    # 指定查询集
    queryset = Reply.objects.all()
    # 指定序列化器
    serializer_class = ReplySerializerForCreate

    # 登录认证
    # permission_classes = [SessionAuthentication, BasicAuthentication]
    def create(self, request, *args, **kwargs):
        user = request.user
        data = request.data
        data['user'] = user.id
        ser = ReplySerializerForCreate(data=data)
        ser.is_valid(raise_exception=True)
        reply = ser.save()
        problem = reply.problem
        if data.get('type') == 2:
            problem.replyname = reply.user.username
            problem.replytime = reply.createtime;
            problem.save()
        return Response({'success': True, 'message': '发表成功'})

    @action(methods=['put'], detail=True)
    def useful(self, request, pk):
        try:
            user = request.user
        except:
            user = None
        # 判断登录
        if user.is_authenticated and user is not None:
            # 创建redis连接对象
            conn = get_redis_connection('question')
            # 查询标识数据,如果有,代表点击过
            flag = conn.hget('reply_useful_%s' % user.id, pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            # 进行保存操作
            reply = self.get_object()
            reply.useful_count += 1
            reply.save()
            # 设置一个是否点击过的标识
            conn.hset('reply_useful_%s' % user.id, pk, '你的温柔无人能及')
            return Response({'success': True, 'message': '操作成功'})
        else:
            return Response({'success': False, 'message': '请先登录'})

    @action(methods=['put'], detail=True)
    def unuseful(self, request, pk):
        try:
            user = request.user
        except:
            user = None
        # 判断登录
        if user.is_authenticated and user is not None:
            # 创建redis连接对象
            conn = get_redis_connection('question')
            # 查询标识数据,如果有,代表点击过
            flag = conn.hget('reply_useful_%s' % user.id, pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            # 进行保存操作
            reply = self.get_object()
            reply.unuseful_count += 1
            reply.save()
            # 设置一个是否点击过的标识
            conn.hset('reply_useful_%s' % user.id, pk, '你的温柔无人能及')
            return Response({'success': True, 'message': '操作成功'})
        else:
            return Response({'success': False, 'message': '请先登录'})

    @action(methods=['put'], detail=True)
    def focusin(self, request, pk):
        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            label = self.get_object()
            if user not in label.users.all():
                label.users.add(user)
                label.save()
                return Response({'success': True, 'message': '关注成功'})
            else:
                return Response({'success': True, 'message': '已经关注了...'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

    # labels/{pk}/focusout/  取消关注标签
    @action(methods=['put'], detail=True)
    def focusout(self, request, pk):
        try:
            user = self.request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            label = self.get_object()
            if user in label.users.all():
                label.users.remove(user)
                label.save()
                return Response({'success': True, 'message': '取消关注成功'})
            else:
                return Response({'success': True, 'message': '已经取消关注了...'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)
